package org.vsg.security.model.presentation.spring;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.apps.HttpApplicationContext;
import org.vsg.common.pagination.apps.HttpPaginationApplicationContextFactory;
import org.vsg.common.pagination.apps.PaginationApplicationContext;
import org.vsg.common.pagination.apps.RecordLimitCarrierApplicationContext;
import org.vsg.common.pagination.carrier.HttpSingleSortRecordLimitCarrier;
import org.vsg.common.pagination.carrier.RecordLimitCarrier;
import org.vsg.common.web.json.ListResult;
import org.vsg.common.web.json.SubmitResult;
import org.vsg.common.web.json.processor.JsTimestampJsonValueProcessor;
import org.vsg.security.model.domain.UrlResource;
import org.vsg.security.model.service.UrlResourceService;
import org.vsg.security.model.vo.json.UrlResourceListVO;
import org.vsg.security.model.vo.json.UrlResourceVO;


@Controller
public class UrlController {

	private final static Logger logger = LoggerFactory.getLogger(UrlController.class);	
	
	@Autowired	
	private UrlResourceService urlResourceService;

	@Autowired	
	//private RegistedURLService registedUrlService;
	
	
	@RequestMapping("/pageRegistedUrlResource.do")	
	public String pageRegistedUrlResource(HttpServletRequest req , HttpServletResponse res) throws Exception {
		
		// generate pagination application and set the request
		PaginationApplicationContext pageAppsContext = HttpPaginationApplicationContextFactory.getPaginationContext(req);
		// set parameter passed in pagination url
		RecordLimitCarrierApplicationContext recordLimitAppsContenxt = (RecordLimitCarrierApplicationContext)pageAppsContext;
		
		HttpApplicationContext httpContext = (HttpApplicationContext)pageAppsContext;
		
		httpContext.addParameterName("url");
		
		// set the data to attribute
		RecordLimitCarrier limitCarrier = recordLimitAppsContenxt.generateRecordLimitCarrier( HttpSingleSortRecordLimitCarrier.class );
		
		Pagination page = urlResourceService.pageUrlResource(limitCarrier);
		
		
		Collection<UrlResource> resourceList = page.getPaginationList();
		
		Collection<UrlResourceListVO> tmpVoList = new Vector<UrlResourceListVO>();
		for (UrlResource urlRes : resourceList) {
			tmpVoList.add(new UrlResourceListVO( urlRes ));
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults( page.getTotalRecord() );
		lr.setRows( tmpVoList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		// --- set attribute ---
		req.setAttribute("json", jsonObject);
		
		return "json";
	}
	
	@RequestMapping("/registedUrlResources.do")	
	public String registedUrlResources(HttpServletRequest req , HttpServletResponse res , String[] regUrlId) throws Exception {

		Collection<UrlResource> mapUrlResources = new Vector<UrlResource>();
		//RegistedURL regUrl = null;
		UrlResource urlResource = null;
		for (String id : regUrlId) {
			/*
			regUrl = registedUrlService.loadRegistedURL( new Integer(id));
			
			urlResource = new UrlResource();
			urlResource.setCode( regUrl.getCode() );
			urlResource.setDescription( regUrl.getDescription() );
			urlResource.setName( regUrl.getName() );
			urlResource.setUrl( regUrl.getMap() );
			urlResource.setContext( regUrl.getModule().getCode());
			
			mapUrlResources.add( urlResource );
			*/

		}		
		// get the business service

		for (UrlResource urlRes : mapUrlResources) {
			urlResourceService.addUrlResource( urlRes );
		}
		

		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "注册URL成功!" );
	
		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);			
		
		return "result";
	}

	@RequestMapping("/unregistedUrlResources.do")	
	public String unregistedUrlResources(HttpServletRequest req , HttpServletResponse res , String[] resourceId) throws Exception {
		
		
		Collection<UrlResource> removeResources = new Vector<UrlResource>();
		UrlResource urlResource = null;
		for (String id : resourceId) {
			urlResource = new UrlResource();
			urlResource.setId( new Long(id) );
			removeResources.add( urlResource );
		}
		
		// ---- remove resource ----
		for (UrlResource urlRes : removeResources) {
			urlResourceService.deleteUrlResource(urlRes);
		}
		
		
		// --- json result object ---
		SubmitResult submitResult = new SubmitResult();
		submitResult.setSuccess(true);
		submitResult.setMsg( "移除URL数据成功!" );

		JSONObject jsonObject = JSONObject.fromObject(submitResult ); 
		
		req.setAttribute("json", jsonObject);
		
		// --- use log show
		logger.info(jsonObject.toString());			
		
		return "result";
	}

	@RequestMapping("/listModuleOrContext.do")	
	public String listModuleOrContext(HttpServletRequest req , HttpServletResponse res) throws Exception {

	
		Collection<String> allContext = urlResourceService.findAllContext();
		
		Collection<Map> contextList = new Vector<Map>();
		
		Map<String , String> map = null;
		for (String context : allContext) {
			map = new HashMap<String , String>();
			map.put("code", context);
			map.put("name", context);
			contextList.add( map );
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults(contextList.size());
		lr.setRows( contextList );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		req.setAttribute("json", jsonObject);
		
		// --- use log show
		logger.info(jsonObject.toString());		
		
		return "json";
	}

	@RequestMapping("/listForUrlContext.do")		
	public String listForUrlContext(HttpServletRequest req , HttpServletResponse res ,  String context) throws Exception {

		
		Collection<UrlResource> allUrlResource =  urlResourceService.findUrlResourcesByContext(context);
		
		Collection<UrlResourceVO> allUrlResourceVO = new Vector<UrlResourceVO>();
		
		for (UrlResource urlResource : allUrlResource) {
			allUrlResourceVO.add( new UrlResourceVO(urlResource) );
		}
		
		// --- parse the json ---
		ListResult lr = new ListResult();
		lr.setResults(allUrlResourceVO.size());
		lr.setRows( allUrlResourceVO );
		
		JsonConfig jcfg = new JsonConfig();
		jcfg.registerJsonValueProcessor(java.sql.Timestamp.class, new JsTimestampJsonValueProcessor());
		JSONObject jsonObject = JSONObject.fromObject(lr ,jcfg ); 
		
		req.setAttribute("json", jsonObject);
		
		// --- use log show
		logger.info(jsonObject.toString());		
		return "json";
	}
	
}
